var roleManage = function() {

    var _init = function() {

        var table = $('#table_role');

        var tableUnit=table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
            	url:url+"s",
//            	url:"/a/biz/products",
            },
            "autoWidth": false,
//          "scrollX": true,
            "columns": [/*{
                    "width": " 5%",
                    "data": "id"
                },*/{
                    "width": "119px",
                    "data": "name"
                },
                {
                    "width": "86px",
                    "data": "levelId",
                    "render": function(data, type, row, meta) {
                    	var val=data;
                    	if(data!=null&&data!=''){
            				$.ajax({
            					url : '/a/biz/alevel/obj',
            					type : 'post',
            					dataType : 'json',
            					contentType:"application/json; charset=utf-8",
            					async: false,
            					data : JSON.stringify({ id: data }),
            				}).done(function(r) {
            					if (r.status === '1') {
            						val=r.data.name;

            					} else if (r.status === '2') {
            					}
            				});
            				return val;
                    	}else
                    		return "";	
                    }
                },
                {
                    "width": "75px",
                    "data": "type"
                },
                {
                    "width": "120px",
                    "data": "phone"
                },
                {
                    "width": "80px",
                    "data": "province"
                },
                {

                    "width": "80px",

                    "data": "city"
                },
               {
                    "width": "100px",
                    "data": "null",
                    "render":function(data, type, row, meta) {
                    	return row.totalCount-row.leftCount
                    }
                }, {
                    "width": "100px",
                    "data": "leftCount"
                },
                {
                    "width": "100px",
                    "data": "updateOper"
                },
               {
                    "width": "75px",

                    "data": "isActive",
                    "render": function(data, type, row, meta) {
                    	if(data=='0'){
                    		return "停用";	
                    	}else{
                    		return "正常";	
                    	}
                    }
                }, 
                {
                    "width": "100px",
                    "data": "createDate",
                    "render": function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD');
                    }
                },
                {
                	"width": "475px",
                    "data": "isActive",
                    "render": function(data, type, row, meta) {
                    var buttonStr="";
                    if(agentType=='总部'){
	                    if(row.type=='普通'){
	                    	buttonStr="<button type=\"button\" class=\"btn  btn_upType_role\">升级</button><button type=\"button\" class=\"btn  btn_change_role\">转移</button>";
	                    }else  if(row.type=='分销商'){
	                    	buttonStr="<button type=\"button\" class=\"btn  btn_downType_role\">降级</button><button type=\"button\" class=\"btn  btn_change_role\">转移</button>";
	                    }
                    }
                    if(data=='0'){
                   	   return "<button type=\"button\" class=\"btn  btn_edit_role\">修改</button><button type=\"button\" class=\"btn  btn_detail_role\">详情</button><button type=\"button\" class=\"btn yellow btn_repwd_role\">重置密码</button><button type=\"button\" class=\"btn red btn_qy_role\">启用</button>"+buttonStr
                    }else{
                 	   return "<button type=\"button\" class=\"btn  btn_edit_role\">修改</button><button type=\"button\" class=\"btn  btn_detail_role\">详情</button><button type=\"button\" class=\"btn yellow btn_repwd_role\">重置密码</button><button type=\"button\" class=\"btn red btn_del_role\">禁用</button>"+buttonStr

                    }
                   }
                }
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."

            },
            "pageLength": 5,
            "order": [
                [10, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0, 11]
            }  ,/*{
                "targets": 8,
                "render": function(data, type, row, meta) {
                	var val=data;
                	if(data!=null&&data!=''){

        				$.ajax({
        					url : '/a/sys/operator',
        					type : 'post',
        					dataType : 'json',
        					contentType:"application/json; charset=utf-8",
        					async: false,
        					data : JSON.stringify({ id: data }),
        				}).done(function(r) {
        					if (r.status === '1') {
        						val=r.data.name;

        					} else if (r.status === '2') {
        					}
        				});
        				return val;
                	}else
                		return "";	
                }
            },*/ {
                "targets": 9,
               
            }],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'row'<'col-md-5'i><'col-md-7'>p>",
            "fnInitComplete": function() {},
            "fnDrawCallback": function(){
          	/*　　var api = this.api();
          	　　var startIndex= api.context[0]._iDisplayStart;//获取到本页开始的条数
          	　　api.column(0).nodes().each(function(cell, i) {
          	　　　　cell.innerHTML = startIndex + i + 1;
          	　　}); */
          	}
        });

     /*   // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .alert').css('display', 'none'); // 隐藏提示头
            $('.modal .form-group').removeClass('has-error'); //清除错误信息
            $('.modal input[type="text"]').val(''); // 清空 input
            $('.modal input[type="checkbox"]').prop('checked', false); // 清空 input
        });*/
       
       
       
        // 发布商品
        $('#btn_new_role').click(function(event) {
        	window.location.href="/p/biz/agent/edit?id=null"; 
        });
        // 取消
        $('#btn_cancle').click(function(event) {
        	window.location.href="/p/biz/agent";
        });
        // 修改
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
        	window.location.href="/p/biz/agent/edit?id="+ encodeURIComponent(_id);
        });

        
        // 详情
        table.on('click', '.btn_detail_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
        	window.location.href="/p/biz/agent/detail?id="+ encodeURIComponent(_id);
        });

        
        $('#doQuery').click(function(event){
  		  var province =   $("#distpicker1 select[name='province']").val();
  		  var city =   $("#distpicker1 select[name='city']").val();
  		  var name =   $("#search input[name='name']").val();
  		  var start =   $("#datepicker input[name='start']").val();
  		  var end =   $("#datepicker input[name='end']").val();
  		  var phone =   $("#search input[name='phone']").val();
  		  var levelId =   $("#search select[name='levelId']").val();
  		  var param={"province":province,"city":city,"name":name,"phone":phone,"levelId":levelId,"createDate":start,"updateDate":end};
  		  $('#table_role').DataTable().search(JSON.stringify(param)  ).draw();
  		$(' .help-block').html(''); 
//          table.DataTable().ajax.reload();

  		  
  		});
        
        // 禁用
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要禁用？",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            // alert('提交删除');
                            var _data = JSON.stringify({ id: _id });
                            request_role_del(_data, function(res) {
                                // 正确
                                table.DataTable().ajax.reload();
                            }, function(err) {
                                //	错误
                            	$(' .help-block').html(err); 
                        		$(' .help-block').css('color','red'); 
                            })
                        }
                    }
                }
            });
        });
        
        // 禁用
        table.on('click', '.btn_qy_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要启用？",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            // alert('提交删除');
                            var _data = JSON.stringify({ id: _id });
                            request_role_del(_data, function(res) {
                                // 正确
                                table.DataTable().ajax.reload();
                            }, function(err) {
                                //	错误
                            	$(' .help-block').html(err); 
                        		$(' .help-block').css('color','red'); 
                            })
                        }
                    }
                }
            });
        });
        
        
        //分销降为普通
        table.on('click', '.btn_downType_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要降级吗？",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                        	
                    		$.ajax({
                    			url : '/a/biz/downType',
                    			type : 'PUT',
                    			dataType : 'json',
                    			contentType:"application/json; charset=utf-8",
                    			data : JSON.stringify({ id: _id }),
                    		}).done(function(data) {
                    			if (data.status === '1') {
                    				// 正确
                    				  table.DataTable().ajax.reload();
                    			} else if (data.status === '2') {
//                    				  //	错误
                                	$(' .help-block').html(data.message); 
                            		$(' .help-block').css('color','red'); 
                    			}
                    		});
                    		
                        }
                    }
                }
            });
        });
        
        
        // 普通升级为分销
        table.on('click', '.btn_upType_role', function(event) {
        	  //分销降为普通
                var oData_arr = table.DataTable().rows($(this).parents("tr"))
                    .data(); // 操作行对象
                var _id = oData_arr[0].id;
                bootbox.dialog({
                    message: "确定要升级吗？",
                    title: "提示",
                    buttons: {
                        cancel: {
                            label: "取消",
                            className: "btn dark btn-outline"
                        },
                        success: {
                            label: "确定",
                            className: "btn green",
                            callback: function() {
                            	
                        		$.ajax({
                        			url : '/a/biz/upType?i=1',
                        			type : 'PUT',
                        			dataType : 'json',
                        			contentType:"application/json; charset=utf-8",
                        			data : JSON.stringify({ id: _id }),
                        		}).done(function(data) {
                        			if (data.status === '1') {
                        				// 正确
                        				  table.DataTable().ajax.reload();
                        			} else if (data.status === '2') {
//                        				  //	错误
                                    	$(' .help-block').html(data.message); 
                                		$(' .help-block').css('color','red'); 
                        			}
                        		});
                        		
                            }
                        }
                    }
                });
            });
            
        
        
        //代理商转移
        table.on('click', '.btn_change_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            var parentId=oData_arr[0].parentId;
            $('.change-link').modal('hide');
            showAgentList(_id,parentId);
            $('.change-link').modal('show');
            selectId=_id;
         
        });
        
        
        // 重置密码
        table.on('click', '.btn_repwd_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要重置密码吗？(默认重置为123456)",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                        	
							$.ajax({
								 url: '/a/biz/agentpwd',
								 type: 'put',
								 dataType: 'json',
								 contentType:"application/json; charset=utf-8",
								 data: JSON.stringify({
										id : _id
									}),
								 })
								 .done(function(data) {
									 table.DataTable().ajax.reload();
								 });
                        }
                    }
                }
            });
        });
    }

    return {
        init: function() {
            _init();
        }

    };

}();

function getPwdandAd(){
	  var phone =   $("input[name='phone']").val();
	  $("input[name='loginName']").val(phone);
	  $("input[name='password']").val(phone);
	};
	




$('#qBeginTime').datepicker({  
    todayBtn : "linked",  
    autoclose : true,  
    todayHighlight : true,  
    endDate : new Date()  
}).on('changeDate',function(e){  
    var startTime = e.date;  
    $('#qEndTime').datepicker('setStartDate',startTime);  
});  
//结束时间：  
$('#qEndTime').datepicker({  
    todayBtn : "linked",  
    autoclose : true,  
    todayHighlight : true,  
    endDate : new Date()  
}).on('changeDate',function(e){  
    var endTime = e.date;  
    $('#qBeginTime').datepicker('setEndDate',endTime);  
});


// 确定添加
//$("#form_role_new").find('button[type=submit]').click(function() {
	$("#modal_sure_new").click(function() {
    var _data = $("#form_role_new").serializeObject();
    var _id=_data.id;
	var param={"agent":{"phone":_data.phone,"id":_id,"contractName":_data.contractName,"levelId":_data.levelId,"totalCount":_data.totalCount,"levelCode":_data.levelCode,"templateId":_data.templateId,
		                  "name":_data.name,"province":_data.province,"city":_data.city,"address":_data.address,
		                  "type":_data.type,"isUseCoupon":_data.isUseCoupon},
		       "operater":{"loginName":_data.loginName,"password":_data.password,"phone":_data.phone}
		       }
	if (!mdTool.validate(_data.phone, 'require')) {
		mdTool.showMessage('请输入手机号码');
		return;
	}if (!mdTool.validate(_data.phone, 'phone')) {
		mdTool.showMessage('手机号码格式不正确，请重新输入');
		return;
	}
	if (!mdTool.validate(_data.contractName, 'require')) {
		mdTool.showMessage('请输入代理商联系人');
		return;
	}if (!mdTool.validate(_data.levelId, 'require')) {
		mdTool.showMessage('请选择代理商级别');
		return;
	}if (!mdTool.validate(_data.totalCount, 'require')) {
		mdTool.showMessage('请输入代理套数');
		return;
	}
	/*if (!mdTool.validate(_data.templateId, 'require')) {
		mdTool.showMessage('请选择模板');
		return;
	}*/if (!mdTool.validate(_data.type, 'require')) {
		mdTool.showMessage('请选择类型');
		return;
	}if (!mdTool.validate(_data.name, 'require')) {
		mdTool.showMessage('请输入代理商名称');
		return;
	}if (!mdTool.validate(_data.province, 'require')) {
		mdTool.showMessage('请输入省份');
		return;
	}if (!mdTool.validate(_data.city, 'require')) {
		mdTool.showMessage('请输入城市');
		return;
	}if (_data.totalCount>922337203685) {
		mdTool.showMessage('您输入的代理套数太多，请修改');
		return;
	}if (_data.totalCount==0) {
		mdTool.showMessage('您输入的代理套数为0，请修改');
		return;
	}else {
		$(this).attr("disabled","disabled");

		var _type = _id == null||_id == '' ? "put" : "post";

		$.ajax({
			url : '/a/biz/agent',
			type : _type,
			dataType : 'json',
			contentType:"application/json; charset=utf-8",
			data : JSON.stringify(param),
		}).done(function(data) {
			if (data.status === '1') {
				// 正确
	        	window.location.href="/p/biz/agent";

			} else if (data.status === '2') {
//				错误
				mdTool.showMessage(data.message);
				$("#modal_sure_new").attr("disabled",false);

//				$('#modal_new_role .help-block').html(data.message); // 返回错误信息
			}
		}).fail(function(data) {
			$("#modal_sure_new").attr("disabled",false);

		});;
	}
});

	
    $('#levelId').on('change', function(event) {
    	var count=0;
    	 var id=$('input[name="id"]').val();
    	 if(!id){
    	$.get("/a/biz/alevel/getObj?id="+$('#levelId').val(), function(r){
    		
    		var data = r.data;
    		if(data.minCount!=null){
    		 $('input[name="totalCount"]').attr('placeholder',data.minCount+"或以上");
    		}else{
       		 $('input[name="totalCount"]').attr('placeholder',"");

    		}
    		
        });
    	 }
      
    });
    
    
    var storage = window.localStorage;  
    var localAgent = JSON.parse(storage["agent"]);   
    var agentType="";
    if(localAgent){
    	agentType=localAgent.type;
    }
   var selectId ="";   
    function showAgentList(id,parentId){
        var table = $('#table_agent_change');

        var table=table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
            	url:"/a/biz/agentList",
            	data:{"id":id,"parentId":parentId}
            },
            "autoWidth": true,
            "destroy":true,
            "columns": [{
                    "data": "name"
                },
                {
                    "data": "levelId",
                    "render": function(data, type, row, meta) {
                    	var val=data;
                    	if(data!=null&&data!=''){
            				$.ajax({
            					url : '/a/biz/alevel/obj',
            					type : 'post',
            					dataType : 'json',
            					contentType:"application/json; charset=utf-8",
            					async: false,
            					data : JSON.stringify({ id: data }),
            				}).done(function(r) {
            					if (r.status === '1') {
            						val=r.data.name;

            					} else if (r.status === '2') {
            					}
            				});
            				return val;
                    	}else
                    		return "";	
                    }
                },
                {
                    "data": "type"
                },
                {
                    "data": "phone"
                },
                {
                    "data": "province"
                },
                {


                    "data": "city"
                },
               {
                    "data": "null",
                    "render":function(data, type, row, meta) {
                    	return row.totalCount-row.leftCount
                    }
                }, {
                    "data": "leftCount"
                },
           
                {
                    "data": "createDate",
                    "render": function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD');
                    }
                },
                {
                    "data": "null",
                    "defaultContent": "<button type=\"button\" class=\"btn btn_select_role pull-right\">选取</button>"
                }
            ],
            "language": {
            	url: '/assets/pages/Chinese.json'
            },
            "pageLength": 5,
            "order": [
                [8, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0, 9]
            } ],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'row'<'col-md-5'i><'col-md-7'>p>",
            "fnInitComplete": function() {},
            "fnDrawCallback": function(){
          
          	}
        });
        
        
      
    }
    
  //选择代理商
    $('#table_agent_change').on('click', '.btn_select_role', function(event) {
     	var oData_arr =   $('#table_agent_change').DataTable().rows($(this).parents("tr")).data(); // 操作行对象
     	
     	var _id=oData_arr[0].id;
     	  bootbox.dialog({
               message: "确定要转移吗？",
               title: "提示",
               buttons: {
                   cancel: {
                       label: "取消",
                       className: "btn dark btn-outline"
                   },
                   success: {
                       label: "确定",
                       className: "btn green",
                       callback: function() {
                       	
                   		$.ajax({
                   			url : '/a/biz/updateZyAgent',
                   			type : 'POST',
                   			dataType : 'json',
                   			contentType:"application/json; charset=utf-8",
                   			data : JSON.stringify({ id: selectId ,parentId:_id}),
                   		}).done(function(data) {
                   			if (data.status === '1') {
                   				// 正确
                   				 $('.change-link').modal('hide');
                   				 $('#table_role').DataTable().ajax.reload();
                   			} else if (data.status === '2') {
//                   				  //	错误
                   			}
                   		});
                   		
                       }
                   }
               }
           });
     	});
    
    
    
    
    
$(function() {
	
    roleManage.init();
	
	$("table").parent("div").addClass("tabContainer");
	
});